<?php
// Include config file
include_once('./common.php');

// Connect to database
$link = dbConnect();

// Attempt to auth user with database
$user = auth($_POST['username'], $_POST['password']);

if($user == ""){
   	echo "output=badLogin";
	return;
}

//get the userID
$userID = $user['id'];

//clean up the vars
$postID = mysql_real_escape_string($_POST['postID']);
$authorID = mysql_real_escape_string($_POST['authorID']);
$newMessage = mysql_real_escape_string($_POST['newMessage']);
$guestGroupID = mysql_real_escape_string($_POST['guestGroupID']);

//make sure that the person trying to edit this message is allowed to
$query = "SELECT p.userID AS postUserID, p.message, gm.*
			FROM ".TABLE_PREFIX."_posts p, ".TABLE_PREFIX."_groupmembers gm, ".TABLE_PREFIX."_threads t, ".TABLE_PREFIX."_forums f
			WHERE p.postID = $postID
			AND gm.userID = $userID
			AND t.threadID = p.threadID
			AND f.forumID = t.forumID
			AND gm.groupID IN (".$guestGroupID.", f.groupID)";
			
$result = mysql_query($query);
if(!$result){
	echo "output=mySqlError&error=".mysql_error();
	return;
}

//validate authorID sent with one from dbase
$data = mysql_fetch_object($result);

if($authorID != $data->postUserID && $data->isAdmin == 0 && $data->isModerator == 0 || $data->isAllowedToPost == 0){
	echo "output=permissionError";
	return;
}
//store the original message some place for safe keeping
$originalMessage = mysql_real_escape_string($data->message);
$editTime = time();
$result = mysql_query("INSERT INTO ".TABLE_PREFIX."_postedits (postID, userID, message, editTime) VALUES ($postID, $userID, '$originalMessage', $editTime)");
if(!$result){
	echo "output=mySqlError&error=".mysql_error();
	return;
}

//now that that's cleared out of the way, let's edit this bad boy
$result = mysql_query("UPDATE ".TABLE_PREFIX."_posts SET message = '$newMessage' WHERE postID = $postID");
if(!$result){
	echo "output=mySqlError&error=".mysql_error();
	return;
}

//all is well!
echo "output=success";

// Close link to database server
mysql_close($link);
?>